
class OrdersController < ApplicationController

  before_action :require_logined
  before_action :is_self?, :if => proc { params[:reserve_id].present? }

  def new
    if is_reserving?
      @reserve = Reserve.find_by_id_and_user_id!(params[:reserve_id], current_user.id)
    else
      @carts = Cart.by_user_uuid(current_user.uuid)
        .order("id desc").includes([:product => [:main_product_image]])
      if @carts.present?
        @addresses = current_user.addresses
      else
        redirect_to '/'
      end
    end
  end

  def create
    order = if is_reserving?
              reserve = Reserve.find(params[:reserve_id])
              Order.create_order_from_reserving! current_user, reserve.address, reserve.id
            else
              carts = Cart.by_user_uuid(current_user.uuid).includes(:product)
              if carts.blank?
                redirect_to carts_path
                return
              end
              address = current_user.addresses.find(params[:address_id])
              Order.create_order_from_carts!(current_user, address, carts)
            end

    redirect_to generate_pay_payments_path(order_no: order.order_no)
  end

  def callback
  end


    def create_contract_img
      @order = current_user.orders.find(params[:id])
      attachment = @order.build_order_attachment(image: params[:image])

      if attachment.save!
        render json: {
          status: 'ok',
          attachment: attachment
        }
      else
        render json: {
          status: 'error',
          msg: '网络问题，请重试'
        }
      end
      
    end

  private

  def is_reserving?
    params[:reserve_id].present?
  end

  def generate_payment_direct? order
    is_reserving? && order.surveying? && order.reserve.survey_fee.amount <= 0
  end

  def is_self?
    flag = Reserve.where(id: params[:reserve_id], user_id: current_user.id).first
    unless flag
      redirect_to root_url
    end
  end

end
